package com.ht.module.sys.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ht.abnormal.HtException;
import com.ht.constant.AppletConstant;
import com.ht.constant.BusConstant;
import com.ht.constant.DicConstant;
import com.ht.constant.RedisConstant;
import com.ht.module.sys.dto.LoginDto;
import com.ht.module.sys.dto.RegisterDto;
import com.ht.module.sys.entity.SysUser;
import com.ht.module.sys.dto.SysWxUserDto;
import com.ht.module.sys.service.ISysUserRoleService;
import com.ht.module.sys.service.ISysUserService;
import com.ht.module.sys.service.LoginService;
import com.ht.module.sys.vo.LoginVo;
import com.ht.util.*;
import com.wf.captcha.ArithmeticCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @ProjectName: ht
 * @ClassName: LoginController
 * @Author: hejialun
 * @Description: 登录相关接口
 * @Date: 2021/5/18 23:08
 */
@RestController
@RequestMapping("/sys-login")
@Api(tags = "登录相关接口 ")
public class LoginController {
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private LoginService loginService;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysUserRoleService sysUserRoleService;

    @Value("${wxMini.appId}")
    public String appId;
    @Value("${wxMini.secret}")
    public String secret;
    @Value("${password}")
    private String password;

    @ApiOperation("微信登录")
    @RequestMapping(value = "/wxLogin", method = RequestMethod.POST)
    @Transactional
    public JsonResult wxLogin(@RequestBody @Valid SysWxUserDto en) {
        //微信接口服务,通过调用微信接口服务中jscode2session接口获取到openid和session_key
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code=" + en.getCode() + "&grant_type=authorization_code";
        String str = WeChatUtil.httpRequest(url, "GET", null);
        JSONObject jsonObject = JSONObject.parseObject(str);
        //设置openID
        en.setOpenId(jsonObject.getString(AppletConstant.openId));
        en.setUnionId(jsonObject.getString(AppletConstant.unionId));
        SysUser sysUser=null;
        synchronized (this){
            //查询是否注册过
            sysUser= sysUserService.getOne(
                    new QueryWrapper<SysUser>()
                            .eq("open_id", en.getOpenId())
            );
            //判断用户是否存在
            if (BeanUtil.isEmpty(sysUser)) {
                //不存在注册
                sysUser = new SysUser()
                        .setUsername(en.getOpenId())
                        .setPassword(password)
                        .setName("微信用户")
                        .setState(DicConstant.State.ENABLE)
                        .setOpenId(en.getOpenId())
                        .setUnionId(en.getUnionId())
                        .setAvatar(en.getAvatar());
                CommMethod.beanCreate(sysUser);
                sysUserService.registerUser(sysUser);
            }
        }
        //生成token
        LoginVo loginVo = loginService.generateToken(sysUserService.getUserInfoByUsernameAll(sysUser.getUsername()));
        loginVo.getUserInfo().setUsername(null);
        loginVo.getUserInfo().setPassword(null);
        loginVo.getUserInfo().setOpenId(null);
        loginVo.getUserInfo().setUnionId(null);
        //查询吹所有用户信息
        return JsonResult.success(loginVo);
    }


    @ApiOperation("创建验证码")
    @GetMapping(value = "/getCode")
    public JsonResult getCode(String randomStr) throws Exception {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        // 几位数运算，默认是两位
        captcha.setLen(2);
        // 获取运算的结果
        String result = captcha.text();
        // 保存
        redisUtil.set(RedisConstant.VERIFICATION_CODE_PREFIX + randomStr, result, BusConstant.VERIFICATION_CODE_OVERDUE_TIME);
        return JsonResult.success(captcha.toBase64());

    }


    @PostMapping(value = "/login")
    @ApiOperation(value = "登录接口")
    public JsonResult login(@RequestBody @Valid LoginDto en) {
        return JsonResult.success(loginService.login(en));
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @ApiOperation("登出")
    @PostMapping("/logout")
    public JsonResult logout(HttpServletRequest request) {
        loginService.lougout(request);
        return JsonResult.success();
    }


    @ApiOperation("注册账号")
    @PostMapping("/register")
    public JsonResult register(@RequestBody RegisterDto en, HttpServletRequest request) {
        String code = (String) redisUtil.get(BusConstant.EMAIL_CODE + en.getUsername());
        if (StrUtil.isEmpty(code)) {
            throw new HtException("验证码不存在或已过期！");
        }
        //判断验证码是否正确
        if (!en.getCode().equals(code)) {
            throw new HtException("邮箱验证码不正确！");
        }

        SysUser sysUser = new SysUser()
                .setUsername(en.getUsername())
                .setPassword(en.getPassword())
                .setState(DicConstant.State.ENABLE)
                .setName(en.getUsername());

        //注册用户
        sysUserService.registerUser(sysUser);

        //清空redis缓存
        redisUtil.del(BusConstant.EMAIL_CODE + en.getUsername());
        return JsonResult.success("注册成功！");
    }

}